package com.simafei.flow.core.operator.impl;

import cn.hutool.core.util.ClassUtil;
import com.simafei.flow.core.common.Operator;
import com.simafei.flow.core.operator.OperatorHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author fengpengju
 */
@Slf4j
public class OperatorHandlerFactory {

    public static final OperatorHandlerFactory INSTANCE = new OperatorHandlerFactory();

    private final static OperatorHandler DEFAULT_OPERATOR_HANDLER = operator -> false;

    private final List<OperatorHandler> handlers;

    public OperatorHandlerFactory() {
        handlers = new ArrayList<>();

        try {
            for (Class<?> aClass : ClassUtil.scanPackageBySuper(getClass().getPackageName(), OperatorHandler.class)) {
                OperatorHandler function = (OperatorHandler) aClass.getDeclaredConstructor().newInstance();
                handlers.add(function);
            }
        } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
            log.warn("OperatorHandlerFactory init error", e);
        }
    }

    public OperatorHandler getOperatorHandler(Operator operator) {
        for (OperatorHandler handler : handlers) {
            if (handler.support(operator)) {
                return handler;
            }
        }
        return DEFAULT_OPERATOR_HANDLER;
    }
}
